package com.xiang.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiang.reggie.common.Result;
import com.xiang.reggie.entity.Category;
import com.xiang.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 分类管理
 *
 * @author 半山居雾
 * @date 2022/12/15 11:02
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     *
     * @param category 类别
     * @return {@code Result<String>}
     */
    @PostMapping
    public Result<String> save(@RequestBody Category category) {
        log.info("category:{}", category);

        categoryService.save(category);
        return Result.success("新增分类成功");
    }

    /**
     * 查询页面
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @return {@code Result<Page>}
     */
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize) {

        //分页构造器
        Page<Category> categoryPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByDesc(Category::getSort);

        //分页查询，会自动封装到Page中
        categoryService.page(categoryPage, queryWrapper);

        return Result.success(categoryPage);

    }

    /**
     * 更新分类
     *
     * @param category 类别
     * @return {@code Result<String>}
     */
    @PutMapping
    public Result<String> update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        categoryService.updateById(category);
        return Result.success("修改成功");
    }

    /**
     * 删除(排开关联)
     *
     * @param id id
     * @return {@code Result<String>}
     */
    @DeleteMapping
    public Result<String> delete(Long id) {
        log.info("删除分类，id为：{}", id);
//        categoryService.removeById(id);
        categoryService.remove(id);

        return Result.success("分类信息删除成功");
    }

    /**
     * 根据条件查询分类数据
     *
     * @param category 类别
     * @return {@code Result<List<Category>>}
     */
    @GetMapping("/list")
    public Result<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();


        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());

        //排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);


        return Result.success(list);
    }


}
